#include "./fiipRetransmit.h"
static FiipRetransmitStruct* List[10];
static uint8_t listLen = 0;
static uint16_t retransmitTimes = 0;

void fiipRetransmit_add(uint8_t* data, uint16_t dataLen, LinkCfgStruct* link) {
  if (listLen < 10) {
    List[listLen] =
        (FiipRetransmitStruct*)mempool_alloc(sizeof(FiipRetransmitStruct));
    List[listLen]->index =
        (data[format_field_index + 0] << 8) + data[format_field_index + 1];
    List[listLen]->data = (uint8_t*)mempool_alloc(dataLen);
    mem_cpy(List[listLen]->data, data, dataLen);
    List[listLen]->dataLen = dataLen;
    List[listLen]->link = link;
    if (data[format_field_retransmit] == 0x00) {
      List[listLen]->times = 5;
      List[listLen]->interval = 1;
    } else {
      List[listLen]->times = data[format_field_retransmit] >> 4;
      List[listLen]->interval = data[format_field_retransmit] & 0x0F;
    }
    listLen++;
  } else {
    WARN("fiip retransmit list is full.");
  }
}
void fiipRetransmit_del(uint8_t i) {
  FiipRetransmitStruct* retransmit = List[i];
  mempool_free(retransmit->data);
  mempool_free(retransmit);
  List[i] = List[--listLen];
  List[listLen] = NULL;
}
void fiipRetransmit_transmit() {
  FiipRetransmitStruct* retransmit = NULL;
  retransmitTimes++;

  for (uint16_t i = 0; i < listLen; i++) {
    retransmit = List[i];
    if (retransmitTimes % retransmit->interval == 0) {
      fiip_sendOriginal(retransmit->data, retransmit->dataLen,
                        retransmit->link);
      if (--retransmit->times == 0) {
        fiipRetransmit_del(i);
      }
    }
  }
}
void fiipRetransmit_remove(uint16_t index) {
  FiipRetransmitStruct* retransmit = NULL;

  for (uint16_t i = 0; i < listLen; i++) {
    retransmit = List[i];
    if (retransmit->index == index) {
      fiipRetransmit_del(i);
    }
  }
}
